package cn.edu.zime.tjh.iotapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.java_websocket.WebSocket;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.view.Window;

public class DeviceMonitorActivity extends AppCompatActivity {

    private static final String TAG = "DeviceMonitorActivity";
    
    // 界面元素
    private TextView clientInfoTextView;
    private TextView lightValueTextView;
    private TextView locationValueTextView;
    private TextView accelerationValueTextView;
    private Button disconnectButton;
    private View locationCardView;
    
    // 聊天相关界面元素
    private ListView chatListView;
    private EditText messageEditText;
    private Button sendButton;
    private ChatAdapter chatAdapter;
    private List<ChatMessage> chatMessages;
    
    // 存储位置数据
    private double latitude = 0.0;
    private double longitude = 0.0;
    
    // WebSocket连接和客户端信息
    private static WebSocket clientSocket;
    private String clientInfo;
    
    private Button takePhotoButton;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_monitor);
        
        // 初始化界面元素
        clientInfoTextView = findViewById(R.id.clientInfoTextView);
        lightValueTextView = findViewById(R.id.lightValueTextView);
        locationValueTextView = findViewById(R.id.locationValueTextView);
        accelerationValueTextView = findViewById(R.id.accelerationValueTextView);
        disconnectButton = findViewById(R.id.disconnectButton);
        locationCardView = findViewById(R.id.locationCardView);
        
        // 初始化聊天界面元素
        chatListView = findViewById(R.id.chatListView);
        messageEditText = findViewById(R.id.messageEditText);
        sendButton = findViewById(R.id.sendButton);
        
        // 初始化聊天消息列表和适配器
        chatMessages = new ArrayList<>();
        chatAdapter = new ChatAdapter();
        chatListView.setAdapter(chatAdapter);
        
        // 获取客户端信息
        Intent intent = getIntent();
        if (intent != null) {
            clientInfo = intent.getStringExtra("CLIENT_INFO");
            clientInfoTextView.setText("连接的客户端: " + clientInfo);
        }
        
        // 设置位置卡片点击事件
        locationCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到地图界面
                if (latitude != 0.0 || longitude != 0.0) {
                    Intent mapIntent = new Intent(DeviceMonitorActivity.this, LocationActivity.class);
                    mapIntent.putExtra("LATITUDE", latitude);
                    mapIntent.putExtra("LONGITUDE", longitude);
                    mapIntent.putExtra("DEVICE_NAME", clientInfo);
                    startActivity(mapIntent);
                } else {
                    Toast.makeText(DeviceMonitorActivity.this, "暂无位置数据", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        // 设置发送消息按钮点击事件
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendChatMessage();
            }
        });
        
        // 设置断开连接按钮
        disconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnectClient();
                finish();
            }
        });
        
        // 初始化拍照按钮
        takePhotoButton = findViewById(R.id.takePhotoButton);
        takePhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPhoto();
            }
        });
    }
    
    // 静态方法，设置客户端WebSocket连接
    public static void setClientSocket(WebSocket socket) {
        clientSocket = socket;
    }
    
    // 处理客户端发送的数据
    public void handleClientData(final String message) {
        try {
            JSONObject data = new JSONObject(message);
            String type = data.getString("type");
            
            switch (type) {
                case "light":
                    final float lightValue = (float) data.getDouble("value");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            lightValueTextView.setText(String.format("光照强度: %.2f lux", lightValue));
                        }
                    });
                    break;
                    
                case "location":
                    final double latitude = data.getDouble("latitude");
                    final double longitude = data.getDouble("longitude");
                    // 保存位置数据
                    this.latitude = latitude;
                    this.longitude = longitude;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            locationValueTextView.setText(String.format("纬度: %.6f, 经度: %.6f", latitude, longitude));
                        }
                    });
                    break;
                    
                case "acceleration":
                    final float x = (float) data.getDouble("x");
                    final float y = (float) data.getDouble("y");
                    final float z = (float) data.getDouble("z");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            accelerationValueTextView.setText(String.format("X: %.2f m/s², Y: %.2f m/s², Z: %.2f m/s²", x, y, z));
                        }
                    });
                    break;
                    
                case "chat":
                    final String sender = data.getString("sender");
                    final String chatMessage = data.getString("message");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            addChatMessage(sender, chatMessage, false);
                        }
                    });
                    break;
                    
                case "photo":
                    final String base64Image = data.getString("data");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showPhoto(base64Image);
                        }
                    });
                    break;
            }
        } catch (JSONException e) {
            Log.e(TAG, "解析客户端数据错误: " + e.getMessage());
        }
    }
    
    // 发送聊天消息
    private void sendChatMessage() {
        String message = messageEditText.getText().toString().trim();
        if (message.isEmpty()) {
            return;
        }
        
        if (clientSocket != null && clientSocket.isOpen()) {
            try {
                JSONObject chatData = new JSONObject();
                chatData.put("type", "chat");
                chatData.put("sender", "管理员");
                chatData.put("message", message);
                
                clientSocket.send(chatData.toString());
                
                // 添加消息到本地列表
                addChatMessage("管理员", message, true);
                
                // 清空输入框
                messageEditText.setText("");
            } catch (JSONException e) {
                Log.e(TAG, "发送聊天消息错误: " + e.getMessage());
                Toast.makeText(this, "发送消息失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "连接已断开，无法发送消息", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 添加聊天消息到列表
    private void addChatMessage(String sender, String message, boolean isFromMe) {
        ChatMessage chatMessage = new ChatMessage(sender, message, isFromMe);
        chatMessages.add(chatMessage);
        chatAdapter.notifyDataSetChanged();
        
        // 滚动到最新消息
        chatListView.smoothScrollToPosition(chatMessages.size() - 1);
    }
    
    // 断开客户端连接
    private void disconnectClient() {
        if (clientSocket != null && clientSocket.isOpen()) {
            try {
                // 发送断开连接消息
                JSONObject message = new JSONObject();
                message.put("type", "disconnect");
                message.put("message", "管理员已断开连接");
                clientSocket.send(message.toString());
                
                // 关闭连接
                clientSocket.close();
                Toast.makeText(this, "已断开与客户端的连接", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Log.e(TAG, "断开连接错误: " + e.getMessage());
            }
        }
    }
    
    // 请求设备拍照
    private void requestPhoto() {
        if (clientSocket != null && clientSocket.isOpen()) {
            try {
                JSONObject photoRequest = new JSONObject();
                photoRequest.put("type", "photo_request");
                photoRequest.put("message", "请求拍照");
                
                clientSocket.send(photoRequest.toString());
                Toast.makeText(this, "已请求设备拍照，请稍候...", Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                Log.e(TAG, "请求拍照错误: " + e.getMessage());
                Toast.makeText(this, "请求拍照失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "连接已断开，无法请求拍照", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 显示设备拍摄的照片
    private void showPhoto(String base64Image) {
        try {
            // 将Base64字符串转换为Bitmap
            byte[] imageBytes = Base64.decode(base64Image, Base64.DEFAULT);
            final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            
            // 创建对话框显示照片
            final Dialog photoDialog = new Dialog(this);
            photoDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            photoDialog.setContentView(R.layout.dialog_photo_preview);
            
            ImageView photoImageView = photoDialog.findViewById(R.id.photoImageView);
            Button closeButton = photoDialog.findViewById(R.id.closePhotoButton);
            
            photoImageView.setImageBitmap(bitmap);
            
            closeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    photoDialog.dismiss();
                }
            });
            
            photoDialog.show();
        } catch (Exception e) {
            Log.e(TAG, "显示照片错误: " + e.getMessage());
            Toast.makeText(this, "无法显示照片", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onDestroy() {
        // 确保在活动关闭时断开连接
        disconnectClient();
        super.onDestroy();
    }
    
    // 聊天消息数据类
    private static class ChatMessage {
        String sender;
        String message;
        boolean isFromMe;
        
        ChatMessage(String sender, String message, boolean isFromMe) {
            this.sender = sender;
            this.message = message;
            this.isFromMe = isFromMe;
        }
    }
    
    // 聊天消息适配器
    private class ChatAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return chatMessages.size();
        }
        
        @Override
        public ChatMessage getItem(int position) {
            return chatMessages.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(DeviceMonitorActivity.this)
                        .inflate(R.layout.item_chat_message, parent, false);
            }
            
            ChatMessage message = getItem(position);
            
            TextView senderTextView = convertView.findViewById(R.id.senderTextView);
            TextView messageTextView = convertView.findViewById(R.id.messageTextView);
            LinearLayout messageContainer = convertView.findViewById(R.id.messageContainer);
            
            senderTextView.setText(message.sender);
            messageTextView.setText(message.message);
            
            // 根据消息发送方设置不同的样式
            if (message.isFromMe) {
                // 管理员发送的消息靠右对齐
                senderTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
                messageContainer.setGravity(android.view.Gravity.END);
            } else {
                // 设备发送的消息靠左对齐
                senderTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                messageContainer.setGravity(android.view.Gravity.START);
            }
            
            return convertView;
        }
    }
} 